<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.protocol_mapper_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template #menu="{size,row,index}">
        <el-button icon="el-icon-video-play"
                   text
                   type="primary"
                   v-if="permission.protocol_mapper_debug"
                   @click="debugProtocol(row)">调 试</el-button>
      </template>
      <template #menu-form="{row,index,type}">
        <el-button type="success"
                   icon="el-icon-link"
                   @click="debugProtocol()">调试
        </el-button>
      </template>
      <template #inTopicExample-form="{}">
        <code-editor v-model="form.inTopicExample" mode="javascript" height="50px"/>
      </template>
      <template #inBodyExample-form="{}">
        <code-editor v-model="form.inBodyExample" mode="javascript" height="500px"/>
      </template>
      <template #outTopicTemplate-form="{}">
        <code-editor v-model="form.outTopicTemplate" mode="javascript" height="50px"/>
      </template>
      <template #outBodyTemplate-form="{}">
        <code-editor v-model="form.outBodyTemplate" mode="javascript" height="500px"/>
      </template>
    </avue-crud>
    <el-dialog title="协议调试信息"
               v-model="visible"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               width="800">
      <el-row>
        <el-alert type="info" show-icon :closable="false">
          <template #title>
            <el-text size="small">调试功能可直接查看返回数据格式是否正确，具体格式以平台文档为准。</el-text>
          </template>
        </el-alert>
      </el-row>
      <el-row>
        <highlight :code="topicData" language="javascript"/>
      </el-row>
      <el-row>
        <highlight :code="bodyData" language="json"/>
      </el-row>
      <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="closeDebug">关闭</el-button>
              </span>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, debug} from "@/api/iot/protocol/mapper";
import {mapGetters} from "vuex";
import CodeEditor from "@/components/code-editor/main.vue";
import {validatejson, validatenull} from "@/utils/validate";

export default {
  components: {CodeEditor},
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      visible: false,
      topicData: '',
      bodyData: '',
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 32,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        labelWidth: 150,
        menuWidth: 300,
        dialogFullscreen: true,
        column: [
          {
            label: "协议",
            prop: "protocolId",
            type: "select",
            dicUrl: "/blade-iot/protocol/select",
            props: {
              label: "topicName",
              value: "id"
            },
            search: true,
            rules: [{
              required: true,
              message: "请选择协议",
              trigger: "blur"
            }],
          },
          {
            label: "数据流向",
            prop: "flow",
            type: "select",
            dicData: [
              {
                label: '设备到平台',
                value: 'in',
              }, {
                label: '平台到设备',
                value: 'out',
              },
            ],
            width: 120,
            search: true,
            rules: [{
              required: true,
              message: "请选择数据流向",
              trigger: "blur"
            }],
          },
          {
            label: "Topic规则",
            prop: "inTopicReg",
            rules: [{
              required: true,
              message: "请填写输入topic规则",
              trigger: "blur"
            }],
            span: 24,
          },
          {
            label: "输入 topic 示例",
            prop: "inTopicExample",
            rules: [{
              required: true,
              message: "请填写输入topic示例",
              trigger: "blur"
            }],
            slot: true,
          },
          {
            label: "输出 topic 模板",
            prop: "outTopicTemplate",
            rules: [{
              required: true,
              message: "请填写输出的 topic 模板",
              trigger: "blur"
            }],
            slot: true,
          },
          {
            label: "输入 json 示例",
            prop: "inBodyExample",
            rules: [{
              required: true,
              message: "请填写输入的 body json 示例",
              trigger: "blur"
            }],
            slot: true,
            hide: true,
          },
          {
            label: "输出 json 模板",
            prop: "outBodyTemplate",
            rules: [{
              required: true,
              message: "请填写输出 body json 模板",
              trigger: "blur"
            }],
            slot: true,
            hide: true,
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.protocol_mapper_add, false),
        viewBtn: this.validData(this.permission.protocol_mapper_view, false),
        delBtn: this.validData(this.permission.protocol_mapper_delete, false),
        editBtn: this.validData(this.permission.protocol_mapper_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return remove(row.id);
      }).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      });
    },
    debugProtocol(row) {
      const form = validatenull(row) ? this.form : row;
      debug(form).then(res => {
        const data = res.data.data;
        this.visible = true;
        this.topicData = data.topic;
        this.bodyData = data.body;
        if (!validatejson(this.bodyData)) {
          this.$message.warning("输出JSON格式不正确");
        }
      });
    },
    closeDebug() {
      this.visible = false;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
